package smile.fu.hibernatetest;

import static org.junit.Assert.*;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import smile.fu.entity.User;

public class hibernate_bqc {

	@Test
	public void testBQC() {
		Configuration configuration = new Configuration();
		configuration.configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		// 1.指定对哪个表进行操作
		// Criteria criteria = session.createCriteria(User.class);
		// criteria.add(Restrictions.eq("password","9"));
		// criteria.add(Restrictions.like("address", "%江西%"));
		// 模糊查询匹配方式
		// criteria.add(Restrictions.like("address", "江西", MatchMode.ANYWHERE));
		// 添加排序规则
		// criteria.addOrder(Order.desc("password"));
		// 分页 查询前10条数据
		// criteria.setFirstResult(0);//开始位置： (当前页-1)*每页大小
		// criteria.setMaxResults(10);
		// criteria.add()
		// 2.设置操作 得到行数 count
		// criteria.setProjection(Projections.rowCount());
		// Object object = criteria.uniqueResult();
		// 不可以直接从Object类型转换成int;应该先从Object转换成Long类型再转换成int类型
		// int count = (int) object;
		// 正确方式
		// Long lobj = (Long) object;
		// int count = lobj.intValue();
		// System.out.println(count);
		// List<User> userList = criteria.list();
		// for (User user : userList) {
		// System.out.println(user.toString());
		// }

		// 离线查询
		// 1.创建对象，不用session，直接调用DetachedCriteria的静态方法
		// DetachedCriteria detachedCriteria=DetachedCriteria.forClass(User.class);
		// Criteria criteria=detachedCriteria.getExecutableCriteria(session);
		// List<User> list= criteria.list();
		// for (User user : list) {
		// System.out.println(user.toString());
		// }

		transaction.commit();
		session.close();
		sessionFactory.close();
	}

}
